package com.example.config;

import com.example.Service.SysRoleService;
import com.example.Service.SysUserRoleService;
import com.example.Service.SysUserService;
import com.example.model.SysRole;
import com.example.model.SysUser;
import com.example.model.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        //根据用户名称查询用户
        SysUser user = sysUserService.selectByName(name);
        //判断用户是否存在
        if (user == null){
            System.out.println("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }

        //根据用户id查询角色
        List<SysUserRole> userRoles = sysUserRoleService.listByUserId(user.getUser_id());
        for (SysUserRole userRole : userRoles){
            //根据角色id查询角色信息
            SysRole role = sysRoleService.selectById(userRole.getRole_id());
            //角色名称存储到列表中
            authorities.add(new SimpleGrantedAuthority(role.getRole_name()));
        }
        //返回UserDeatils实现类
        //new User是 UserDetails的实现类
        User user1 = new User(user.getUser_name(),user.getUser_psd(),authorities);
        return user1;
    }
}
